﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http.Headers;
using System.Web;
using System.Web.Mvc;
using Html5VideoDemo.Filter;
using Html5VideoDemo.Models;
using Html5VideoDemo.Utility;

namespace Html5VideoDemo.Controllers
{
    public class HomeController : Controller
    {
        private static Random _random;

        static HomeController()
        {
            _random = new Random();
        }

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }

        public ActionResult Video()
        {
            string token = EncryptUtil.GetMd5(_random.Next().ToString());
            ViewBag.Token = token;
            ViewBag.File = "123.mp4";
            //进入视频播放获取一个token值
            HttpCookie cookie = new HttpCookie("z_fileId_1", token);
            cookie.Expires = DateTime.Now.AddMinutes(30);
            base.Response.Cookies.Add(cookie);

            return View();
        }

        /// <summary>
        /// FileContentResult不能实现快进快退,自定义MyFileContentResult 
        /// 通过Session与Cookie的双重校验
        /// </summary>
        /// <param name="f"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public ActionResult Play(string f, string token)
        {
            //Session判断(略)
            //Cookie判断
            HttpCookie cookie = Request.Cookies.Get("z_fileId_1");
            if (cookie == null || cookie.Value != token)
            {
                return HttpNotFound();
            }

            //Range:bytes=0-
            string range = base.Request.Headers.Get("Range");
            if (!String.IsNullOrWhiteSpace(range))
            {
                int start;
                if (!int.TryParse(range.Split('=')[1].Split('-')[0], out start))
                {
                    start = 0;
                }
                return new MyFileContentResult("d:/Logs/test.mp4", start, "video/mp4");
            }
            else
            {
                return HttpNotFound();
            }

        }
    }
}